<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\Context\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CorsMiddleware implements MiddlewareInterface
{
    public function __construct(protected ContainerInterface $container)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);

        $headers = [
            ['name' => 'Access-Control-Allow-Origin', 'value' => '*'],
            ['name' => 'Access-Control-Allow-Methods', 'value' => '*'],
            ['name' => 'Access-Control-Max-Age', 'value' => 86400],
            ['name' => 'Access-Control-Allow-Credentials', 'value' => true],
            ['name' => 'Access-Control-Allow-Headers', 'value' => 'Keep-Alive, User-Agent, Cache-Control, Content-Type, Authorization']
        ];

        foreach ($headers as $header) {
            $response = $response->withHeader($header['name'], $header['value']);
        }

        Context::set(ResponseInterface::class, $response);

        if ($request->getMethod() == 'OPTIONS') {
            return $response;
        }

        return $handler->handle($request);
    }
}
